/*!
 * 浏览器快捷键设置模块
 * @author: __author__
 * @version: __buildVersion__
 * @buildDate：__buildDate__
 */
let version: string = '__buildVersion__';

interface I_HOTKEY {
    key: string,
    ctrlKey: boolean,
    altKey: boolean,
    shiftKey: boolean,
    cmd: string,
    des: string
}

interface I_HOTKEY_FN {
    (...args: any): void
}

interface I_HOTKEY_DATAS {
    hotkeys: I_HOTKEY[],
    cmds: {
        [cmdName: string]: I_HOTKEY_FN
    }
}

/** 配置 */
let config = {
    enable: true
}

let data: I_HOTKEY_DATAS = {
    hotkeys: [],
    cmds: {}
};

/** 设置命令 */
function addCMD(cmdName: string, cmdFn: I_HOTKEY_FN): void {
    data.cmds[cmdName] = cmdFn;
}

/** 移除命令 */
function removeCMD(cmdName: string): void {
    if (data.cmds[cmdName]) {
        delete data.cmds[cmdName];
    }
}

/** 获取命令列表 */
function getCMDs(): any {
    return data.cmds;
}

/** 添加快捷键 sameCover: true 相同覆盖，false: 不覆盖 */
function addHotkey(hotkey: I_HOTKEY, sameCover = false): I_HOTKEY {

    hotkey = Object.assign({
        key: '',
        ctrlKey: false,
        altKey: false,
        shiftKey: false,
        cmd: '',
        des: ''
    }, hotkey);

    // 查找是否有相同快捷键配置
    let sameHotKeyIndex = data.hotkeys.findIndex(hotkey2 => hotkey.key === hotkey2.key && hotkey.ctrlKey === hotkey2.ctrlKey && hotkey.altKey === hotkey2.altKey && hotkey.shiftKey === hotkey2.shiftKey);

    if (sameHotKeyIndex === -1) {
        data.hotkeys.push(hotkey);
    } else if (sameCover) {
        data.hotkeys[sameHotKeyIndex] = hotkey;
    } else {
        data.hotkeys.push(hotkey);
    }

    return hotkey;

}

/** 移除快捷键 */
function removeHotkey(cb: (data: I_HOTKEY) => boolean): void {
    for (let i = data.hotkeys.length - 1; i >= 0; i--) {
        if (cb(data.hotkeys[i]) === true) {
            data.hotkeys.splice(i, 1);
        }
    }
}

/** 获得快捷键列表 */
function getHotkeys(): I_HOTKEY[] {
    return data.hotkeys;
}

window.addEventListener('keydown', evt => {

    if(config.enable){

        for (let i = 0; i < data.hotkeys.length; i++) {
            let hotkey = data.hotkeys[i];
            if (hotkey.key === evt.key && hotkey.ctrlKey === evt.ctrlKey && hotkey.altKey === evt.altKey && hotkey.shiftKey === evt.shiftKey) {
                new Function('cmds', `
                    try{
                        cmds.${hotkey.cmd};
                    }catch(e){
                        throw  'The shortcut command does not exist';
                    }
                `)(data.cmds);
                evt.preventDefault();
            }
        }

    }

});

export default {

    version,
    config,

    // 命令
    addCMD,
    getCMDs,
    removeCMD,

    // 快捷键
    addHotkey,
    getHotkeys,
    removeHotkey

};